﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.DataInteroperabilityTools;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using PlanningGIS.Framework;

using DWGdirect.DatabaseServices;
using DWGdirect.DatabaseServices.Filters;
using DWGdirect.Geometry;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Win32;
using PlanningGIS.Util.Log;


namespace PlanningGIS.DataConvert.model
{
    /// <summary>
    /// 导出E00和dwg
    /// </summary>
    public class E00DwgExport2
    {

        [DllImport("\\DIT.dll")]
        private static extern void ExpE00(IFeatureWorkspace pFws, string strFClassName, IQueryFilter pQf, string strPath);
        private IFeatureLayer mFeatureLayer;
        private IGeometry mFilterGeometry;
        private string mStrFiter;
        private bool mBlnClip;
        private string mStrPath;
        private string mTargetFileNam;
        private IFeatureWorkspace mTempWks;
        private System.Data.DataTable mCadFcodeTable;
       

        private IFeatureClass mClipFcls;
        /// <summary>
        /// 通过委托返回进度条最大值
        /// </summary>
        protected SetProcessBarMax setProcessBarMax;

        /// <summary>
        /// 通过委托返回进度条当前值
        /// </summary>
        protected SetProcessBarCurrent setProcessBarCurrent;
        public E00DwgExport2(IFeatureWorkspace pTempWks, IFeatureLayer pFeatureLayer, IGeometry pFilterGeometry, string strFilter, bool blnClip, string strPath, string strE00FileName)
        {
            mTempWks = pTempWks;
            mFeatureLayer = pFeatureLayer;
            mFilterGeometry = pFilterGeometry;
            mStrFiter = strFilter;
            mBlnClip = blnClip;
            mStrPath = strPath;
            mTargetFileNam = strE00FileName;

        }
        public E00DwgExport2()
        {
        }
        public IFeatureLayer FeatureLayer
        {
            set
            {
                mFeatureLayer = value;
            }
        }

        public IGeometry FilterGeometry
        {
            set
            {
                mFilterGeometry = value;
            }
        }

        public string Filter
        {
            set
            {
                mStrFiter = value;
            }
        }
        public bool Clip
        {
            set
            {
                mBlnClip = value;
            }
        }

        public string Path
        {
            set
            {
                mStrPath = value;
            }
        }
        public string TargetFileName
        {
            set
            {
                mTargetFileNam = value;
            }
        }
        public IFeatureWorkspace TempFeatureWorkspace
        {
            set
            {
                mTempWks = value;
            }
            get
            {
                return mTempWks;
            }
        }
        public System.Data.DataTable CadFcodeTable
        {
            set
            {
                mCadFcodeTable = value;
            }
        }
        
        /// <summary>
        /// 通过委托返回进度条最大值
        /// </summary>
        public SetProcessBarMax SetProcessBarMax
        {
            set { setProcessBarMax = value; }
            get { return setProcessBarMax; }
        }

        /// <summary>
        /// 通过委托返回进度条当前值
        /// </summary>
        public SetProcessBarCurrent SetProcessBarCurrent
        {
            set { setProcessBarCurrent = value; }
            get { return setProcessBarCurrent; }
        }
        public IFeatureClass FeatureClassClip
        {
            set{
                mClipFcls=value;
            }
            get
            {
                 return mClipFcls;
            }


        }
        //public bool ExportDwg(IAcadApplication pAcadApplication, List<IFeatureLayer> pFeaturelayerList, List<string> pFilterList)
        //{
        //    try
        //    {
        //        string strFileName = "";
        //        if (mStrPath.EndsWith("\\"))
        //        {
        //            strFileName = mStrPath + mTargetFileNam + ".dwg";
        //        }
        //        else
        //        {
        //            strFileName = mStrPath + "\\" + mTargetFileNam + ".dwg";
        //        }
        //        if (System.IO.File.Exists(strFileName  ))
        //        {
        //            LogHelper.WriteLog(strFileName + "已经存在");
        //            return true;
        //        }
        //        AcadDocument pAcadDoc;
        //        //if (pAcadApplication.Documents.Count > 0)
        //        //{
        //        //    pAcadDoc = pAcadApplication.Documents.Item(0);

        //        //}
        //        //else
        //        //{
        //            pAcadDoc = pAcadApplication.Documents.Add("acadiso.dwt");
        //        //}
        //        ISymbol pSymbol;
        //        setProcessBarMax(pFeaturelayerList.Count);
        //        for (int i = 0; i < pFeaturelayerList.Count; i++)
        //        {
                   

        //            System.Windows.Forms.Application.DoEvents();                   
        //            IFeatureLayer pFeaturelayer = pFeaturelayerList[i];
        //            string strFilter = pFilterList[i];
        //            IFeatureClass pFcls = pFeaturelayer.FeatureClass;
        //            IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
        //            ISpatialFilter pSpatialFitler = new SpatialFilterClass();
        //            if (mFilterGeometry != null)
        //            {
        //                pSpatialFitler.Geometry = mFilterGeometry;
        //            }
        //            pSpatialFitler.GeometryField = pFcls.ShapeFieldName;
        //            pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
        //            pSpatialFitler.WhereClause = strFilter;
        //            //if (mFilterGeometry.SpatialReference != ((IGeoDataset)pFcls).SpatialReference)
        //            //{
        //            //    mFilterGeometry.Project(((IGeoDataset)pFcls).SpatialReference);
        //            //}
        //            Fcls2Dwg(pFeaturelayer.FeatureClass, pAcadDoc, pSpatialFitler, pFeaturelayer);

        //            setProcessBarCurrent(i + 1);
                    
        //        }
        //        //pAcadApplication.Visible = true;
        //        //pAcadApplication.ZoomExtents();
        //        //pAcadApplication.Visible = false;
           
        //        pAcadDoc.SaveAs(strFileName , AcSaveAsType.acNative, null);
        //        pAcadDoc.SendCommand("-Circle\r2,2,0\r4\r" );
        //      //  AcadSelectionSet ss = pAcadDoc.SelectionSets.Add("test");
        //       // ss.Select(AcSelect.acSelectionSetAll, null, null, System.Type.Missing ,System.Type.Missing );
        //       // pAcadDoc.Export("c:\\aa", "bmp", ss); 
        //        pAcadDoc.Close(false,"");
              

        //        Marshal.ReleaseComObject(pAcadDoc);
        //        pAcadDoc = null;
        //        GC.Collect();
        //        return true;
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return false;
        //    }
        //}

        public bool ExportDwg(  List<IFeatureLayer> pFeaturelayerList, List<string> pFilterList)
        {            
            try
            {
                string strFileName = "";
                if (mStrPath.EndsWith("\\"))
                {
                    strFileName = mStrPath + mTargetFileNam + ".dwg";
                }
                else
                {
                    strFileName = mStrPath + "\\" + mTargetFileNam + ".dwg";
                }
                if (System.IO.File.Exists(strFileName))
                {
                    LogHelper.WriteLog(strFileName + "已经存在");
                    return true;
                }
                Database pDb = new Database(true , false);
                HostApplicationServices.WorkingDatabase = pDb;
                Transaction pTran= pDb.TransactionManager.StartTransaction();
                BlockTable pBt = (BlockTable)pTran.GetObject(pDb.BlockTableId, OpenMode.ForWrite, false);
                BlockTableRecord pBtr = (BlockTableRecord)pTran.GetObject(pBt["*MODEL_SPACE"],  OpenMode.ForWrite, false);
                setProcessBarMax(pFeaturelayerList.Count);
                for (int i = 0; i < pFeaturelayerList.Count; i++)
                {
                    System.Windows.Forms.Application.DoEvents();
                    IFeatureLayer pFeaturelayer = pFeaturelayerList[i];
                    string strFilter = pFilterList[i];
                    IFeatureClass pFcls = pFeaturelayer.FeatureClass;
                    IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
                    ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                    if (mFilterGeometry != null)
                    {
                        pSpatialFitler.Geometry = mFilterGeometry;
                    }
                    pSpatialFitler.GeometryField = pFcls.ShapeFieldName;
                    pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    pSpatialFitler.WhereClause = strFilter;
                  
                    Fcls2Dwg(pFeaturelayer.FeatureClass, pDb,pTran,pBt, pBtr, pSpatialFitler, pFeaturelayer);
                    setProcessBarCurrent(i + 1);

                }

                pDb.UpdateExt(true);
                ViewportTable pViewportTable = pDb.ViewportTableId.GetObject(OpenMode.ForWrite, false, true) as ViewportTable;
                SymbolTableEnumerator pEnum = pViewportTable.GetEnumerator();
                while (pEnum.MoveNext())
                {
                    ViewportTableRecord pView = pEnum.Current.GetObject(OpenMode.ForWrite, false, true) as ViewportTableRecord;
                    pView.CenterPoint = new DWGdirect.Geometry.Point2d((pDb.Extmax.X + pDb.Extmin.X) * 0.5, (pDb.Extmax.Y + pDb.Extmin.Y) * 0.5);
                    pView.Height = pDb.Extmax.Y - pDb.Extmin.Y;
                    pView.Width = pDb.Extmax.X - pDb.Extmin.X;
                }            
                pTran.Commit();
                pDb.SaveAs(strFileName, DwgVersion.vAC18);
                GC.Collect();
                return true;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
        }

        //public bool ExportDwg2(IAcadApplication pAcadApplication, List<IFeatureLayer> pFeaturelayerList, List<string> pFilterList)
        //{
        //    try
        //    {
        //        AcadDocument pAcadDoc;
        //        if (pAcadApplication.Documents.Count > 0)
        //        {
        //            pAcadDoc = pAcadApplication.Documents.Item(0);
        //        }
        //        else
        //        {
        //            pAcadDoc = pAcadApplication.Documents.Add("acadiso.dwt");
        //        }
        //        ISymbol pSymbol;
        //        for (int i = 0; i < pFeaturelayerList.Count; i++)
        //        {
        //            System.Windows.Forms.Application.DoEvents();
        //            IFeatureLayer pFeaturelayer = pFeaturelayerList[i];
        //            string strFilter = pFilterList[i];
        //            IFeatureClass pFcls = pFeaturelayer.FeatureClass;
        //            IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
        //            if (mFilterGeometry != null)
        //            {
        //                ISpatialFilter pSpatialFitler = new SpatialFilterClass();
        //                pSpatialFitler.Geometry = mFilterGeometry;
        //                pSpatialFitler.GeometryField = pFcls.ShapeFieldName;
        //                pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
        //                pSpatialFitler.WhereClause = strFilter;
        //                //if (FeatureLayerHasFeatures(pFeaturelayer, pSpatialFitler) == false) continue;
        //                if (mBlnClip && pFcls.ShapeType != esriGeometryType.esriGeometryPoint & pFcls.FeatureType != esriFeatureType.esriFTAnnotation)
        //                {
        //                    IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
        //                    ClipFeatureClass(pFeaturelayer, pNewFcls, pSpatialFitler, mFilterGeometry);
        //                    System.Windows.Forms.Application.DoEvents();
        //                    Fcls2Dwg(pNewFcls, pAcadDoc, null, pFeaturelayer as IFeatureLayer);
        //                    try
        //                    {
        //                        ((IDataset)pNewFcls).Delete();
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        //MsgHelper.ShowWarningMsgbox(ex.Message);
        //                    }
        //                }
        //                else
        //                {
        //                    IFeatureLayerDefinition pFLayerDef = pFeaturelayer as IFeatureLayerDefinition;
        //                    if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
        //                    {
        //                        Fcls2Dwg(pFcls, pAcadDoc, pSpatialFitler, pFeaturelayer as IFeatureLayer);
        //                    }
        //                    else  //the features in the featurelayer are a subset of features in the featureclass
        //                    {
        //                        IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
        //                        CopyFeatures(pFeaturelayer, pNewFcls, pSpatialFitler);
        //                        System.Windows.Forms.Application.DoEvents();
        //                        if (pNewFcls.FeatureCount(null) == 0) continue;
        //                        Fcls2Dwg(pNewFcls, pAcadDoc, null, pFeaturelayer as IFeatureLayer);
        //                        try
        //                        {
        //                            ((IDataset)pNewFcls).Delete();
        //                        }
        //                        catch (System.Exception)
        //                        {
        //                        }

        //                    }
        //                }
        //            }
        //            else
        //            {
        //                IQueryFilter pFilter = new QueryFilterClass();
        //                pFilter.WhereClause = strFilter;
        //                IFeatureLayerDefinition pFLayerDef = pFeaturelayer as IFeatureLayerDefinition;
        //                if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
        //                {
        //                    if (pFcls.FeatureCount(pFilter) == 0) continue;
        //                    Fcls2Dwg(pFcls, pAcadDoc, pFilter, pFeaturelayer as IFeatureLayer);
        //                }
        //                else
        //                {
        //                    IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
        //                    CopyFeatures(pFeaturelayer, pNewFcls, pFilter);
        //                    System.Windows.Forms.Application.DoEvents();
        //                    if (pNewFcls.FeatureCount(null) == 0) return false;
        //                    Fcls2Dwg(pNewFcls, pAcadDoc, pFilter, pFeaturelayer as IFeatureLayer);
        //                    try
        //                    {

        //                        if (((IDataset)pNewFcls).CanDelete())
        //                        {
        //                            ((IFeatureWorkspaceManage)pFwks).DeleteByName(((IDataset)pNewFcls).FullName as IDatasetName);
        //                            ((IDataset)pNewFcls).Delete();
        //                        }

        //                    }
        //                    catch (System.Exception)
        //                    {
        //                    }

        //                }
        //            }
        //        }
        //        pAcadApplication.Visible = true;
        //        pAcadApplication.ZoomExtents();
        //        pAcadApplication.Visible = false;
        //        string strFileName = "";
        //        if (mStrPath.EndsWith("\\"))
        //        {
        //            strFileName = mStrPath + mTargetFileNam + ".dwg";
        //        }
        //        else
        //        {
        //            strFileName = mStrPath + "\\" + mTargetFileNam + ".dwg";
        //        }
        //        pAcadDoc.SaveAs(strFileName, AcSaveAsType.acNative, null);
        //        return true;
        //    }
        //    catch (System.Exception ex)
        //    {
        //        return false;
        //    }
        //}

        public bool ExportDwg_com(ComObject pAcadApplication, List<IFeatureLayer> pFeaturelayerList, List<string> pFilterList)
        {
            try
            {

                ComObject pAcadDocs = ComObject.CreateInstance(pAcadApplication["Documents"]); ;
                int count = (int)pAcadDocs["Count"];
                ComObject pAcadDoc;
                if (count > 0)
                {
                    // pAcadDoc = pAcadApplication.Documents.Item(0);
                    //pAcadDoc = ComObject.CreateInstance(pAcadApplication["Documents", 0]);
                    pAcadDoc = ComObject.CreateInstance(pAcadDocs.InvokeMethod("Item", 0));


                }
                else
                {
                    // pAcadDoc = pAcadApplication.Documents.Add("acadiso.dwt");
                    pAcadDoc = ComObject.CreateInstance(pAcadDocs.InvokeMethod("Add", System.Reflection.Missing.Value, System.Reflection.Missing.Value, 1, 4));
                }
                for (int i = 0; i < pFeaturelayerList.Count; i++)
                {
                    System.Windows.Forms.Application.DoEvents();
                    IFeatureLayer pFeaturelayer = pFeaturelayerList[i];
                    string strFilter = pFilterList[i];
                    IFeatureClass pFcls = pFeaturelayer.FeatureClass;
                    IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
                    if (mFilterGeometry != null)
                    {
                        ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                        pSpatialFitler.Geometry = mFilterGeometry;
                        pSpatialFitler.GeometryField = pFcls.ShapeFieldName;
                        pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        pSpatialFitler.WhereClause = strFilter;
                        //if (FeatureLayerHasFeatures(pFeaturelayer, pSpatialFitler) == false) continue;
                        if (mBlnClip && pFcls.ShapeType != esriGeometryType.esriGeometryPoint & pFcls.FeatureType != esriFeatureType.esriFTAnnotation)
                        {
                            IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                            ClipFeatureClass(pFcls, pNewFcls, pSpatialFitler, mFilterGeometry);
                            System.Windows.Forms.Application.DoEvents();
                            Fcls2Dwg2(pNewFcls, pAcadDoc, null, pFeaturelayer as IFeatureLayer);
                            try
                            {
                                ((IDataset)pNewFcls).Delete();
                            }
                            catch (Exception ex)
                            {
                                MsgHelper.ShowWarningMsgbox(ex.Message);
                            }
                        }
                        else
                        {
                            IFeatureLayerDefinition pFLayerDef = pFeaturelayer as IFeatureLayerDefinition;
                            if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
                            {
                                Fcls2Dwg2(pFcls, pAcadDoc, pSpatialFitler, pFeaturelayer as IFeatureLayer);
                            }
                            else  //the features in the featurelayer are a subset of features in the featureclass
                            {
                                IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                                CopyFeatures(pFcls, pNewFcls, pSpatialFitler);
                                System.Windows.Forms.Application.DoEvents();
                                if (pNewFcls.FeatureCount(null) == 0) continue;
                                Fcls2Dwg2(pNewFcls, pAcadDoc, null, pFeaturelayer as IFeatureLayer);
                                try
                                {
                                    ((IDataset)pNewFcls).Delete();
                                }
                                catch (System.Exception)
                                {
                                }

                            }
                        }
                    }
                    else
                    {
                        IQueryFilter pFilter = new QueryFilterClass();
                        pFilter.WhereClause = strFilter;
                        IFeatureLayerDefinition pFLayerDef = pFeaturelayer as IFeatureLayerDefinition;
                        if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
                        {
                            if (pFcls.FeatureCount(pFilter) == 0) continue;
                            Fcls2Dwg2(pFcls, pAcadDoc, pFilter, pFeaturelayer as IFeatureLayer);
                        }
                        else
                        {
                            IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                            CopyFeatures(pFeaturelayer, pNewFcls, pFilter);
                            System.Windows.Forms.Application.DoEvents();
                            if (pNewFcls.FeatureCount(null) == 0) return false;
                            Fcls2Dwg2(pNewFcls, pAcadDoc, pFilter, pFeaturelayer as IFeatureLayer);
                            try
                            {

                                if (((IDataset)pNewFcls).CanDelete())
                                {
                                    ((IFeatureWorkspaceManage)pFwks).DeleteByName(((IDataset)pNewFcls).FullName as IDatasetName);
                                    ((IDataset)pNewFcls).Delete();
                                }

                            }
                            catch (System.Exception)
                            {
                            }

                        }
                    }
                }
                pAcadApplication["Visible"] = true;
                //pAcadApplication.ZoomExtents();
                pAcadApplication.InvokeMethod("ZoomExtents");
                pAcadApplication["Visible"] = false;
                string strFileName = "";
                if (mStrPath.EndsWith("\\"))
                {
                    strFileName = mStrPath + mTargetFileNam + ".dwg";
                }
                else
                {
                    strFileName = mStrPath + "\\" + mTargetFileNam + ".dwg";
                }
                //pAcadDoc.SaveAs(strFileName, AcSaveAsType.acNative, null);
                pAcadDoc.InvokeMethod("SaveAs", strFileName,36, System.Reflection.Missing.Value);
                return true;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }

        }

        private void SetTextStyle(IAcadDocument pAcadDoc)
        {
            if (pAcadDoc.TextStyles.Count > 0)
            {
                AcadTextStyle pTxtStyle = pAcadDoc.TextStyles.Item(0);
                string strTypeFace; bool blnBold, blnItatic; int charSet, pictchAndFamily;
                pTxtStyle.GetFont(out strTypeFace, out blnBold, out blnItatic, out charSet, out pictchAndFamily);
                pTxtStyle.SetFont("宋体", blnBold, blnItatic, charSet, pictchAndFamily);
            }
        }
        //private void Fcls2Dwg(IFeatureClass pFcls,AcadDocument pAcadDoc,IQueryFilter pFilter,IFeatureLayer  pFLayer )
        //{
        //    LogHelper.WriteLog("开始导出图层'"+pFLayer.Name +"'");
        //    try
        //    {
        //        DwgExportUtility pDwgEpUtility = new DwgExportUtility();
        //        pDwgEpUtility.AcadDocument = pAcadDoc;
        //        IFeatureCursor pFcursor = pFcls.Search(pFilter, false);
        //        string strCadLayerName = "";

        //        AcadLayer pCadLayer= pDwgEpUtility.CreateCadLayer(pFLayer.Name);
        //        strCadLayerName = pCadLayer == null ? "0" : pCadLayer.Name;
        //        Marshal.ReleaseComObject(pCadLayer);
        //        pCadLayer = null;
        //        IFeature pFeature = pFcursor.NextFeature();
        //        int totalCount = 0;
        //        int successCount = 0;
        //        IAcadEntity pCadEnt;
        //        IGeometry pGeometry;
        //        System.Windows.Forms.Application.DoEvents();
        //        while (pFeature != null)
        //        {
        //            totalCount++;
        //            if (totalCount % 10 == 0) System.Windows.Forms.Application.DoEvents();
        //            try
        //            {
        //                ISymbol pSymbol = null;
        //                if (pFLayer is IGeoFeatureLayer)
        //                {
        //                    pSymbol = ((IGeoFeatureLayer)pFLayer).Renderer.get_SymbolByFeature(pFeature);
        //                }
        //                if (pFcls.FeatureType == esriFeatureType.esriFTAnnotation)
        //                {
        //                    IAnnotationFeature pAnnotationFeature = pFeature as IAnnotationFeature;
        //                    IAnnotationClassExtension pAnnoFclsExtension = pFcls.Extension as IAnnotationClassExtension;
        //                    double dblReferenceScale = pAnnoFclsExtension.ReferenceScale;
        //                    IAcadText pCadTxt = pDwgEpUtility.Esri2CadText(pAnnotationFeature.Annotation as ITextElement, strCadLayerName, dblReferenceScale);
        //                    if (pCadTxt != null)
        //                    {
        //                        successCount++;
        //                        Marshal.ReleaseComObject(pCadTxt);
        //                        pCadTxt = null;
        //                    }
        //                    else
        //                    {
        //                        LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
        //                    }
        //                }
        //                else
        //                {
        //                    if (pFcls.ShapeType == esriGeometryType.esriGeometryPoint)
        //                    {
                               
        //                        string strStyle = GetStyleByFeature(pFeature);
        //                        double dblAngle = GetAngleByFeature(pFeature);
        //                        string strBlockFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + @"\blocks\" + strStyle + ".dwg";
        //                        if (System.IO.File.Exists(strBlockFile) == false)
        //                        {
        //                            strBlockFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + @"\blocks\gc200.dwg";
        //                        }

        //                        IAcadBlockReference pBlock = pDwgEpUtility.EsriPt2CadBlock(pFeature.Shape as IPoint, strBlockFile, dblAngle, strCadLayerName);
        //                        if (pBlock != null)
        //                        {
        //                            successCount++;
        //                            SaveCadEntProperty(pFeature, pBlock);
        //                            Marshal.ReleaseComObject(pBlock);
        //                            pBlock = null;
        //                        }
        //                        else
        //                        {
        //                            LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
        //                        }
        //                    }
        //                    else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolyline)
        //                    {
        //                        AcadAcCmColor pCadColor = null;
        //                        string strStyle = GetStyleByFeature(pFeature);
        //                        if (pSymbol is ILineSymbol)
        //                        {
        //                            try
        //                            {
        //                                ILineSymbol pLineSymbol = pSymbol as ILineSymbol;
        //                                IRgbColor pRgbColor = pLineSymbol.Color as IRgbColor;
        //                                if (pRgbColor != null)
        //                                {
        //                                    pCadColor = pAcadDoc.Application.GetInterfaceObject("AutoCAD.AcCmColor.17") as AcadAcCmColor;
        //                                    if (pRgbColor.Red == 0 & pRgbColor.Blue == 0 & pRgbColor.Green == 0)
        //                                    {
        //                                        pCadColor.SetRGB(255, 255, 255);
        //                                    }
        //                                    else
        //                                    {
        //                                        pCadColor.SetRGB(pRgbColor.Red, pRgbColor.Green, pRgbColor.Blue);
        //                                    }
        //                                }
        //                            }
        //                            catch (System.Exception)
        //                            {
        //                            }
        //                        }
        //                        pGeometry = pFeature.Shape;
        //                        if (mBlnClip)
        //                        {
        //                            //pGeometry = ClipGeometry(pGeometry);
        //                            pGeometry = GeometryHelper.CutFeatByPolygon(pGeometry, mFilterGeometry, pGeometry.Dimension);
        //                            if (pGeometry == null || pGeometry.IsEmpty)
        //                            {
        //                                pFeature = null;
        //                                pFeature = pFcursor.NextFeature();
        //                                successCount++;
        //                                continue;
        //                            }
        //                        }
        //                        if (pGeometry.IsEmpty == false)
        //                        {
        //                            List<IAcadLWPolyline> pCadPolylines = pDwgEpUtility.Esri2CadPolyline(pGeometry as IPolyline, strCadLayerName, pCadColor, strStyle);
        //                            if (pCadPolylines.Count > 0)
        //                            {
        //                                successCount++;
        //                                foreach (IAcadLWPolyline pCadPolyline in pCadPolylines)
        //                                {

        //                                    SaveCadEntProperty(pFeature, pCadPolyline);
        //                                    if (pCadPolyline != null)
        //                                    {
        //                                        Marshal.ReleaseComObject(pCadPolyline);

        //                                    }
        //                                }
        //                            }
        //                            else
        //                            {
        //                                LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
        //                            }
        //                            if (pCadColor != null)
        //                            {
        //                                Marshal.ReleaseComObject(pCadColor);
        //                                pCadColor = null;
        //                            }
        //                        }
        //                    }
        //                    else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolygon)
        //                    {
        //                        AcadAcCmColor pCadColor = null;
        //                        if (pSymbol is IFillSymbol)
        //                        {
        //                            try
        //                            {
        //                                IFillSymbol pFillSymbol = pSymbol as IFillSymbol;
        //                                IRgbColor pRgbColor = pFillSymbol.Color as IRgbColor;
        //                                if (pRgbColor != null)
        //                                {
        //                                    pCadColor = pAcadDoc.Application.GetInterfaceObject("AutoCAD.AcCmColor.17") as AcadAcCmColor;
        //                                    pCadColor.SetRGB(pRgbColor.Red, pRgbColor.Green, pRgbColor.Blue);
        //                                }
        //                            }
        //                            catch (System.Exception)
        //                            {
        //                            }
        //                        }
        //                        pGeometry = pFeature.Shape;
        //                        if (mBlnClip)
        //                        {
        //                            //pGeometry = ClipGeometry(pGeometry);
        //                            pGeometry = GeometryHelper.CutFeatByPolygon(pGeometry, mFilterGeometry, pGeometry.Dimension);
        //                            if (pGeometry == null || pGeometry.IsEmpty)
        //                            {
        //                                pFeature = null;
        //                                pFeature = pFcursor.NextFeature();
        //                                successCount++;
        //                                continue;
        //                            }
        //                        }
        //                        IAcadRegion pCadRegion = pDwgEpUtility.Esri2CadRegion(pGeometry as IPolygon, strCadLayerName, pCadColor);
        //                        if (pCadRegion != null)
        //                        {
        //                            successCount++;
        //                            SaveCadEntProperty(pFeature, pCadRegion);
        //                            Marshal.ReleaseComObject(pCadRegion);
        //                            pCadRegion = null;
        //                        }
        //                        else
        //                        {
        //                            LogHelper.WriteLog("ID为"+pFeature.OID +"的要素导出失败");
        //                        }
        //                        if (pCadColor != null)
        //                        {
        //                            Marshal.ReleaseComObject(pCadColor);
        //                            pCadColor = null;
        //                        }

        //                    }
        //                }
        //            }
        //            catch (System.Exception) { }
        //            Marshal.ReleaseComObject(pFeature);
        //            pFeature = null;
        //            pFeature = pFcursor.NextFeature();
        //        }
        //        Marshal.ReleaseComObject(pFcursor);
        //        LogHelper.WriteLog("图层'" + pFLayer.Name + "' 导出完毕,成功导出要素个数:" + successCount + ";失败导出的要素个数:" + (totalCount - successCount));
        //    }
        //    catch (System.Exception ex)
        //    {
        //        LogHelper.WriteLog("图层'" + pFLayer.Name + "' 导出时候出错，错误信息:" + ex.Message);
        //    }
        //}

        private void Fcls2Dwg(IFeatureClass pFcls, Database pDb,Transaction pTran, BlockTable pBt, BlockTableRecord pBtr, IQueryFilter pFilter, IFeatureLayer pFLayer)
        {
            LogHelper.WriteLog("开始导出图层'" + pFLayer.Name + "'");
            try
            {
                DwgExportUtility2 pDwgEpUtility = new DwgExportUtility2();
                pDwgEpUtility.Db = pDb;
                IFeatureCursor pFcursor = pFcls.Search(pFilter, false);
                string strCadLayerName = "";

                bool bln = pDwgEpUtility.CreateCadLayer(pFLayer.Name);
                strCadLayerName = bln ?  pFLayer.Name:"0" ;
            
                IFeature pFeature = pFcursor.NextFeature();
                int totalCount = 0;
                int successCount = 0;
              
                IGeometry pGeometry;
                System.Windows.Forms.Application.DoEvents();
                while (pFeature != null)
                {
                    totalCount++;
                    if (totalCount % 10 == 0) System.Windows.Forms.Application.DoEvents();
                    try
                    {
                        ISymbol pSymbol = null;
                        if (pFLayer is IGeoFeatureLayer)
                        {
                            pSymbol = ((IGeoFeatureLayer)pFLayer).Renderer.get_SymbolByFeature(pFeature);
                        }
                        if (pFcls.FeatureType == esriFeatureType.esriFTAnnotation)
                        {
                            IAnnotationFeature pAnnotationFeature = pFeature as IAnnotationFeature;
                            IAnnotationClassExtension pAnnoFclsExtension = pFcls.Extension as IAnnotationClassExtension;
                            double dblReferenceScale = pAnnoFclsExtension.ReferenceScale;
                          DBText txt = pDwgEpUtility.Esri2CadText(pTran,pBtr, pAnnotationFeature.Annotation as ITextElement, strCadLayerName, dblReferenceScale);
                            if (txt !=null )
                            {
                                successCount++;                             
                            }
                            else
                            {
                                LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
                            }
                        }
                        else
                        {
                            if (pFcls.ShapeType == esriGeometryType.esriGeometryPoint)
                            {
                                string strStyle = GetStyleByFeature(pFeature);
                                double dblAngle = GetAngleByFeature(pFeature);
                                string strBlockFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + @"\blocks\" + strStyle + ".dwg";
                                if (System.IO.File.Exists(strBlockFile) == false)
                                {
                                    strBlockFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + @"\blocks\gc200.dwg";
                                }
                                BlockReference pBlock = pDwgEpUtility.EsriPt2CadBlock(pDb,pTran,pBt,pBtr, pFeature.Shape as IPoint, strBlockFile, dblAngle, strCadLayerName);
                                if (pBlock != null)
                                {
                                    successCount++;
                                    SaveCadEntProperty(pDb, pTran, pFeature, pBlock);
                                    //Marshal.ReleaseComObject(pBlock);
                                    pBlock = null;
                                }
                                else
                                {
                                    LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
                                }
                            }
                            else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolyline)
                            {
                                DWGdirect.Colors.Color pCadColor = null;
                                string strStyle = GetStyleByFeature(pFeature);
                                if (pSymbol is ILineSymbol)
                                {
                                    try
                                    {
                                        ILineSymbol pLineSymbol = pSymbol as ILineSymbol;
                                        IRgbColor pRgbColor = pLineSymbol.Color as IRgbColor;
                                        if (pRgbColor != null)
                                        {                                          
                                            if (pRgbColor.Red == 0 & pRgbColor.Blue == 0 & pRgbColor.Green == 0)
                                            {
                                                pCadColor = DWGdirect.Colors.Color.FromRgb(255, 255, 255);                                               
                                            }
                                            else
                                            {
                                                pCadColor = DWGdirect.Colors.Color.FromRgb((byte)pRgbColor.Red, (byte)pRgbColor.Green, (byte)pRgbColor.Blue);                                                             
                                            }
                                        }
                                    }
                                    catch (System.Exception)
                                    {
                                    }
                                }
                                pGeometry = pFeature.Shape;
                                if (mBlnClip)
                                {
                                    //pGeometry = ClipGeometry(pGeometry);
                                    pGeometry = GeometryHelper.CutFeatByPolygon(pGeometry, mFilterGeometry, pGeometry.Dimension);
                                    if (pGeometry == null || pGeometry.IsEmpty)
                                    {
                                        pFeature = null;
                                        pFeature = pFcursor.NextFeature();
                                        successCount++;
                                        continue;
                                    }
                                }
                                if (pGeometry.IsEmpty == false)
                                {
                                    List<DWGdirect.DatabaseServices.Polyline> pCadPolylines = pDwgEpUtility.Esri2CadPolyline(pTran,pBtr, pGeometry as IPolyline, strCadLayerName, pCadColor, strStyle);
                                    if (pCadPolylines.Count > 0)
                                    {
                                        successCount++;
                                        foreach (DWGdirect.DatabaseServices.Polyline pCadPolyline in pCadPolylines)
                                        {                                            
                                            SaveCadEntProperty(pDb,pTran, pFeature, pCadPolyline);
                                            if (pCadPolyline != null)
                                            {
                                                //Marshal.ReleaseComObject(pCadPolyline);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
                                    }
                                    if (pCadColor != null)
                                    {
                                        //Marshal.ReleaseComObject(pCadColor);
                                        pCadColor = null;
                                    }
                                }
                            }
                            else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolygon)
                            {
                                DWGdirect.Colors.Color pCadColor = null;
                                if (pSymbol is IFillSymbol)
                                {
                                    try
                                    {
                                        IFillSymbol pFillSymbol = pSymbol as IFillSymbol;
                                        IRgbColor pRgbColor = pFillSymbol.Color as IRgbColor;
                                        if (pRgbColor != null)
                                        {
                                            pCadColor = DWGdirect.Colors.Color.FromRgb((byte)pRgbColor.Red, (byte)pRgbColor.Green, (byte)pRgbColor.Blue);
                                        }
                                    }
                                    catch (System.Exception)
                                    {
                                    }
                                }
                                pGeometry = pFeature.Shape;
                                if (mBlnClip)
                                {
                                    //pGeometry = ClipGeometry(pGeometry);
                                    pGeometry = GeometryHelper.CutFeatByPolygon(pGeometry, mFilterGeometry, pGeometry.Dimension);
                                    if (pGeometry == null || pGeometry.IsEmpty)
                                    {
                                        pFeature = null;
                                        pFeature = pFcursor.NextFeature();
                                        successCount++;
                                        continue;
                                    }
                                }
                               List<Region> regions = pDwgEpUtility.Esri2CadRegion(pTran,pBtr, pGeometry as IPolygon, strCadLayerName, pCadColor);
                               if (regions.Count>0)
                                {
                                    successCount++;
                                   foreach(Region region in regions)
                                   {

                                    SaveCadEntProperty(pDb,pTran, pFeature, region);                                
                                   }
                                   
                                }
                                else
                                {
                                    LogHelper.WriteLog("ID为" + pFeature.OID + "的要素导出失败");
                                }
                                if (pCadColor != null)
                                {
                                    //Marshal.ReleaseComObject(pCadColor);
                                    pCadColor = null;
                                }

                            }
                        }
                    }
                    catch (System.Exception) { }
                    Marshal.ReleaseComObject(pFeature);
                    pFeature = null;
                    pFeature = pFcursor.NextFeature();
                }
                Marshal.ReleaseComObject(pFcursor);
                LogHelper.WriteLog("图层'" + pFLayer.Name + "' 导出完毕,成功导出要素个数:" + successCount + ";失败导出的要素个数:" + (totalCount - successCount));
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog("图层'" + pFLayer.Name + "' 导出时候出错，错误信息:" + ex.Message);
            }
        }

        private void Fcls2Dwg2(IFeatureClass pFcls, ComObject  pAcadDoc, IQueryFilter pFilter, IFeatureLayer pFLayer)
        {
            DwgExportUtility pDwgEpUtility = new DwgExportUtility();
            pDwgEpUtility.AcadDocument2 = pAcadDoc;
            IFeatureCursor pFcursor = pFcls.Search(pFilter, false);
            
            pDwgEpUtility.CreateCadLayer2(pFLayer.Name);
            IFeature pFeature = pFcursor.NextFeature();

            while (pFeature != null)
            {
                ISymbol pSymbol = null;
                if (pFLayer is IGeoFeatureLayer)
                {
                    pSymbol = ((IGeoFeatureLayer)pFLayer).Renderer.get_SymbolByFeature(pFeature);
                }
                if (pFcls.FeatureType == esriFeatureType.esriFTAnnotation)
                {
                    //IAnnotationFeature pAnnotationFeature = pFeature as IAnnotationFeature;
                    //IAcadText pCadTxt = pDwgEpUtility.Esri2CadText(pAnnotationFeature.Annotation as ITextElement, pFLayer.Name);
                    //if (pCadTxt != null)
                    //{
                    //    Marshal.ReleaseComObject(pCadTxt);
                    //    pCadTxt = null;
                    //}
                }
                else
                {
                    if (pFcls.ShapeType == esriGeometryType.esriGeometryPoint)
                    {
                        //IAcadPoint pCadPt = pDwgEpUtility.Esri2CadPt(pFeature.Shape as IPoint, pFLayer.Name);
                        //if (pCadPt != null)
                        //{
                        //    SaveCadEntProperty(pFeature, pCadPt);
                        //    Marshal.ReleaseComObject(pCadPt);
                        //    pCadPt = null;
                        //}

                    }
                    else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolyline)
                    {
                        //AcadAcCmColor pCadColor = null;
                        //if (pSymbol is ILineSymbol)
                        //{
                        //    try
                        //    {
                        //        ILineSymbol pLineSymbol = pSymbol as ILineSymbol;
                        //        IRgbColor pRgbColor = pLineSymbol.Color as IRgbColor;
                        //        pCadColor = pAcadDoc.Application.GetInterfaceObject("AutoCAD.AcCmColor.17") as AcadAcCmColor;
                        //        if (pRgbColor.Red == 0 & pRgbColor.Blue == 0 & pRgbColor.Green == 0)
                        //        {
                        //            pCadColor.SetRGB(255, 255, 255);
                        //        }
                        //        else
                        //        {
                        //            pCadColor.SetRGB(pRgbColor.Red, pRgbColor.Green, pRgbColor.Blue);
                        //        }

                        //    }
                        //    catch (System.Exception)
                        //    {
                        //    }
                        //}
                        List<ComObject > pCadPolylines = pDwgEpUtility.Esri2CadPolyline2(pFeature.Shape as IPolyline, pFLayer.Name, null );
                        //foreach (IAcadLWPolyline pCadPolyline in pCadPolylines)
                        //{
                        //    SaveCadEntProperty(pFeature, pCadPolyline);
                        //    if (pCadPolyline != null)
                        //    {
                        //        Marshal.ReleaseComObject(pCadPolyline);
                                
                        //    }
                        //}
                    }
                    else if (pFcls.ShapeType == esriGeometryType.esriGeometryPolygon)
                    {
                        //AcadAcCmColor pCadColor = null;
                        //if (pSymbol is IFillSymbol)
                        //{
                        //    try
                        //    {
                        //        IFillSymbol pFillSymbol = pSymbol as IFillSymbol;
                        //        IRgbColor pRgbColor = pFillSymbol.Color as IRgbColor;
                        //        pCadColor = pAcadDoc.Application.GetInterfaceObject("AutoCAD.AcCmColor.17") as AcadAcCmColor;
                        //        pCadColor.SetRGB(pRgbColor.Red, pRgbColor.Green, pRgbColor.Blue);
                        //    }
                        //    catch (System.Exception)
                        //    {
                        //    }
                        //}
                        ComObject  pCadRegion = pDwgEpUtility.Esri2CadRegion2(pFeature.Shape as IPolygon, pFLayer.Name, null );
                        //if (pCadRegion != null)
                        //{
                        //    SaveCadEntProperty(pFeature, pCadRegion);

                        //    Marshal.ReleaseComObject(pCadRegion);
                        //    pCadRegion = null;
                        //}

                    }
                }

                pFeature = pFcursor.NextFeature();
            }
            Marshal.ReleaseComObject(pFcursor);

        }
        //private void SaveCadEntProperty(Database pDb,Transaction pTran, IFeature pFeature, Entity pEnt)
        //{
        //    ResultBuffer objResultBuffer = null;                    
        //    RegAppTable regAppTable = pTran.GetObject(pDb.RegAppTableId, OpenMode.ForWrite, false) as RegAppTable;                   
        //    try
        //    {
        //        IFields pFlds = pFeature.Fields;
        //        int count = pFlds.FieldCount;
        //        IField pFld;
             
               
        //        string strFldName = "";
        //        for (int i = 0; i < count; i++)
        //        {
        //            pFld = pFlds.get_Field(i);
        //            strFldName = pFld.Name.ToUpper();
        //            if (pFld.Name == "分类代码" || pFld.Name == "代码" || pFld.Name == "要素代码" || pFld.Name == "CODE" || pFld.Name=="FCODE")
        //            {
        //                strFldName = "FCODE";
        //                if (pFeature.get_Value(i) != DBNull.Value)
        //                {
                           
        //                    if (!regAppTable.Has("SOUTH"))
        //                    {
        //                        RegAppTableRecord regAppTableRecord = new RegAppTableRecord();
        //                        regAppTableRecord.Name = "SOUTH";
        //                        regAppTable.Add(regAppTableRecord);
        //                        pTran.AddNewlyCreatedDBObject(regAppTableRecord, true);
        //                    }

        //                    string strSouth_Code = GetSouthCode(pFeature.get_Value(i).ToString());                         
        //                    objResultBuffer = new ResultBuffer();
        //                    objResultBuffer.Add(new TypedValue(1001, "SOUTH"));
        //                    objResultBuffer.Add(new TypedValue(1002, "{"));
        //                    objResultBuffer.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, strSouth_Code));
        //                    objResultBuffer.Add(new TypedValue(1002, "}"));
        //                    pEnt.XData = objResultBuffer;
        //                }
        //            }
        //            if (pFld.Name.ToLower() == "shape_area" || pFld.Name.ToLower() == "shape_length" || pFld.Name.ToLower() == "shape_len") continue;
        //            //if (pFld.Type == esriFieldType.esriFieldTypeDouble || pFld.Type == esriFieldType.esriFieldTypeSingle)
        //            //{
        //            //    if (!regAppTable.Has(strFldName))
        //            //    {
        //            //        RegAppTableRecord regAppTableRecord = new RegAppTableRecord();
        //            //        regAppTableRecord.Name = strFldName;
        //            //        regAppTable.Add(regAppTableRecord);
        //            //        pTran.AddNewlyCreatedDBObject(regAppTableRecord, true);
        //            //    }
        //            //    objResultBuffer = new ResultBuffer();
        //            //    objResultBuffer.Add(new TypedValue(1001, strFldName));
        //            //    objResultBuffer.Add(new TypedValue(1002, "{"));
        //            //    objResultBuffer.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, pFeature.get_Value(i) == DBNull.Value ? "0" : pFeature.get_Value(i).ToString()));  
        //            //    objResultBuffer.Add(new TypedValue(1002, "}"));
        //            //    pEnt.XData = objResultBuffer;
        //            //}
        //            //else if (pFld.Type == esriFieldType.esriFieldTypeInteger || pFld.Type == esriFieldType.esriFieldTypeSmallInteger)
        //            //{
        //            //    if (!regAppTable.Has(strFldName))
        //            //    {
        //            //        RegAppTableRecord regAppTableRecord = new RegAppTableRecord();
        //            //        regAppTableRecord.Name = strFldName;
        //            //        regAppTable.Add(regAppTableRecord);
        //            //        pTran.AddNewlyCreatedDBObject(regAppTableRecord, true);
        //            //    }
        //            //    objResultBuffer = new ResultBuffer();
        //            //    objResultBuffer.Add(new TypedValue(1001, strFldName));
        //            //    objResultBuffer.Add(new TypedValue(1002, "{"));
        //            //    objResultBuffer.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, pFeature.get_Value(i) == DBNull.Value ? "0" : pFeature.get_Value(i).ToString()));
        //            //    objResultBuffer.Add(new TypedValue(1002, "}"));
        //            //    pEnt.XData = objResultBuffer;
        //            //}
        //            //else if (pFld.Type == esriFieldType.esriFieldTypeString || pFld.Type == esriFieldType.esriFieldTypeDate)
        //            //{
        //            //    if (!regAppTable.Has(strFldName))
        //            //    {
        //            //        RegAppTableRecord regAppTableRecord = new RegAppTableRecord();
        //            //        regAppTableRecord.Name = strFldName;
        //            //        regAppTable.Add(regAppTableRecord);
        //            //        pTran.AddNewlyCreatedDBObject(regAppTableRecord, true);
        //            //    }
        //            //    objResultBuffer = new ResultBuffer();
        //            //    objResultBuffer.Add(new TypedValue(1001, strFldName));
        //            //    objResultBuffer.Add(new TypedValue(1002, "{"));
        //            //    objResultBuffer.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, pFeature.get_Value(i) == DBNull.Value ? "0" : pFeature.get_Value(i).ToString()));
        //            //    objResultBuffer.Add(new TypedValue(1002, "}"));
        //            //    pEnt.XData = objResultBuffer;                       
        //            //}
        //        }
        //    }
        //    catch (System.Exception ex)
        //    {
        //    }
        //    finally
        //    {
        //    }
        //}
        private void SaveCadEntProperty(Database pDb, Transaction pTran, IFeature pFeature, Entity pEnt)
        {
           
            try
            {
                IFields pFlds = pFeature.Fields;
                int count = pFlds.FieldCount;
                IField pFld;

                string strFldName = "";
                for (int i = 0; i < count; i++)
                {
                    object value=pFeature.get_Value(i);
                    if (value == DBNull.Value) continue;
                    pFld = pFlds.get_Field(i);
                    strFldName = pFld.Name.ToUpper();
                    if (pFld.Name == "分类代码" || pFld.Name == "代码" || pFld.Name == "要素代码" || pFld.Name == "CODE" || pFld.Name == "FCODE")
                    {
                        SaveXData(pDb, pEnt, "FCODE", pFeature.get_Value(i).ToString(), (int)DxfCode.ExtendedDataAsciiString);
                        string strSouth_Code = GetSouthCode(pFeature.get_Value(i).ToString());
                        SaveXData(pDb, pEnt, "SOUTH", strSouth_Code, (int)DxfCode.ExtendedDataAsciiString);
                    }
                    if (pFld.Name.ToLower() == "shape_area" || pFld.Name.ToLower() == "shape_length" || pFld.Name.ToLower() == "shape_len") continue;
                    if (pFld.Name == (pFeature.Class as IFeatureClass).ShapeFieldName) continue;
                    SaveXData(pDb, pEnt, pFld.Name, value.ToString(), (int)DxfCode.ExtendedDataAsciiString);                   
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            finally
            {
            }
        }
        public static void SaveXData(Database pDb, Entity pEntity, string strRegAppName, object objXDataValue, int nDxfCode)
        {           
            Transaction pTran = null;
            try
            {                
                ResultBuffer objResultBuffer = null;
                pTran = pDb.TransactionManager.StartTransaction();               
                RegAppTable regAppTable = pTran.GetObject(pDb.RegAppTableId, OpenMode.ForWrite, false) as RegAppTable;
                RegAppTableRecord regAppTableRecord = new RegAppTableRecord();
                regAppTableRecord.Name = strRegAppName;
                if (!regAppTable.Has(strRegAppName))
                {
                    regAppTable.Add(regAppTableRecord);
                    pTran.AddNewlyCreatedDBObject(regAppTableRecord, true);
                }
                try
                {
                    objResultBuffer = new ResultBuffer();
                    objResultBuffer.Add(new TypedValue(1001, strRegAppName));
                    objResultBuffer.Add(new TypedValue(1002, "{"));
                    objResultBuffer.Add(new TypedValue(nDxfCode, objXDataValue));
                    objResultBuffer.Add(new TypedValue(1002, "}"));
                    pEntity.XData = objResultBuffer;
                }
                catch (System.Exception ex)
                {
                    LogHelper.WriteLog(ex);             
                }
                pTran.Commit();

            }           
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            finally
            {
                pTran.Dispose();         
            }
        }

        private void SaveCadEntProperty(IFeature pFeature, IAcadEntity pEnt)
        {
            try
            {
                IFields pFlds = pFeature.Fields;
                int count = pFlds.FieldCount;
                IField pFld;
                //dxfcode: string(1000),int(1071),float(1040),  扩展数据的注册应用程序名(1001),扩展数据控制字符串（“{”或“}”） (1002)

                short[] xdataType = new short[4] { 1001, 1002, 0, 1002 };
                object[] xdataValue = new object[4] { null, "{", null, "}" };
                string strFldName = "";
                for (int i = 0; i < count; i++)
                {
                    pFld = pFlds.get_Field(i);
                    strFldName = pFld.Name.ToUpper();
                    if (pFld.Name == "分类代码" || pFld.Name == "代码" || pFld.Name == "要素代码" || pFld.Name == "CODE" || pFld.Name=="FCODE")
                    {
                        strFldName = "FCODE";
                        if (pFeature.get_Value(i) != DBNull.Value)
                        {
                            string strSouth_Code = GetSouthCode(pFeature.get_Value(i).ToString());
                            xdataType[2] = 1000;
                            xdataValue[0] = "SOUTH";
                            xdataValue[2] = strSouth_Code; 
                            pEnt.SetXData(xdataType, xdataValue); 
                        }
                    }
                    if (pFld.Name.ToLower() == "shape_area" || pFld.Name.ToLower() == "shape_length" || pFld.Name.ToLower() == "shape_len") continue;
                    if (pFld.Type == esriFieldType.esriFieldTypeDouble || pFld.Type == esriFieldType.esriFieldTypeSingle)
                    {
                        xdataType[2] = 1040;
                        xdataValue[0] = strFldName;
                        xdataValue[2] = pFeature.get_Value(i) == DBNull.Value ? 0 : pFeature.get_Value(i);
                        pEnt.SetXData(xdataType, xdataValue);
                    }
                    else if (pFld.Type == esriFieldType.esriFieldTypeInteger || pFld.Type == esriFieldType.esriFieldTypeSmallInteger)
                    {
                        xdataType[2] = 1071;
                        xdataValue[0] = strFldName;
                        xdataValue[2] = pFeature.get_Value(i) == DBNull.Value ? 0 : pFeature.get_Value(i);
                        pEnt.SetXData(xdataType, xdataValue);
                    }
                    else if (pFld.Type == esriFieldType.esriFieldTypeString || pFld.Type == esriFieldType.esriFieldTypeDate)
                    {
                        xdataType[2] = 1000;
                        xdataValue[0] = strFldName;
                        xdataValue[2] = pFeature.get_Value(i) == DBNull.Value ? 0 : pFeature.get_Value(i);
                        pEnt.SetXData(xdataType, xdataValue);                        
                    }
                }
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
            finally
            {
            }

        }
        public bool ExportE00()
        {
            if (mFeatureLayer == null) return false;
            try
            {
                DirectoryInfo pDirec = new DirectoryInfo(System.IO.Path.GetDirectoryName(AppConfig.StartupPath));
                pDirec.CreateSubdirectory("DitTempFolder");
                IFeatureClass pFcls = mFeatureLayer.FeatureClass;
                IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
                ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                pSpatialFitler.Geometry = mFilterGeometry;
                pSpatialFitler.GeometryField = mFeatureLayer.FeatureClass.ShapeFieldName;
                pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                pSpatialFitler.WhereClause = mStrFiter;
                if (mFilterGeometry != null && mBlnClip && (pFcls.ShapeType == esriGeometryType.esriGeometryPolygon || pFcls.ShapeType == esriGeometryType.esriGeometryPolyline))
                {
                    IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                    ClipFeatureClass(pFcls, pNewFcls, pSpatialFitler, mFilterGeometry);
                    ExpE00(((IDataset)pNewFcls).Workspace as IFeatureWorkspace, ((IDataset)pNewFcls).Name, pSpatialFitler, mStrPath);
                    try
                    {
                        ((IDataset)pNewFcls).Delete();
                    }
                    catch (Exception ex)
                    {
                        MsgHelper.ShowWarningMsgbox(ex.Message);
                    }
                    //if (File.Exists(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00"))
                    //{
                    //    File.Copy(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00", mStrPath + "\\" + mTargetFileNam + ".e00", true);
                    //    File.Delete(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00");
                    //}
                }
                else
                {
                    ExpE00(pFwks, ((IDataset)pFcls).Name, pSpatialFitler, mStrPath);
                }
                System.Windows.Forms.Application.DoEvents();
                return true;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
        }
        /*
        public bool ExportE00()
        {
            if (mFeatureLayer == null) return false;
            try
            {
                DirectoryInfo pDirec = new DirectoryInfo(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location));
                pDirec.CreateSubdirectory("DitTempFolder");
                IFeatureClass pFcls = mFeatureLayer.FeatureClass;
                IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
                if (mFilterGeometry != null)
                {
                    ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                    pSpatialFitler.Geometry = mFilterGeometry;
                    pSpatialFitler.GeometryField = mFeatureLayer.FeatureClass.ShapeFieldName;
                    pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                    pSpatialFitler.WhereClause = mStrFiter;
                    if (FeatureLayerHasFeatures(mFeatureLayer, pSpatialFitler) == false) return false;
                    if (mBlnClip && pFcls.ShapeType != esriGeometryType.esriGeometryPoint & pFcls.FeatureType != esriFeatureType.esriFTAnnotation)
                    {
                        IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);

                        ClipFeatureClass(pFcls, pNewFcls, pSpatialFitler, mFilterGeometry);
                        ExpE00(((IDataset)pNewFcls).Workspace as IFeatureWorkspace, ((IDataset)pNewFcls).Name, pSpatialFitler, mStrPath);

                        try
                        {
                            ((IDataset)pNewFcls).Delete();
                        }
                        catch (Exception ex)
                        {
                            MsgHelper.ShowWarningMsgbox(ex.Message);
                        }
                        if (File.Exists(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00"))
                        {
                            File.Copy(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00", mStrPath + "\\" + mTargetFileNam + ".e00", true);
                            File.Delete(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00");
                        }
                    }
                    else
                    {
                        IFeatureLayerDefinition pFLayerDef = mFeatureLayer as IFeatureLayerDefinition;
                        if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
                        {
                            ExpE00(pFwks, ((IDataset)pFcls).Name, pSpatialFitler, mStrPath);
                        }
                        else  //the features in the featurelayer are a subset of features in the featureclass
                        {
                            IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                            CopyFeatures(pFcls, pNewFcls, pSpatialFitler);
                            if (pNewFcls.FeatureCount(null) == 0) return false;
                            ExpE00(pFwks, ((IDataset)pNewFcls).Name, pSpatialFitler, mStrPath);
                            try
                            {
                                ((IDataset)pNewFcls).Delete();
                            }
                            catch (System.Exception)
                            {
                            }
                            if (File.Exists(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00"))
                            {
                                File.Copy(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00", mStrPath + "\\" + mTargetFileNam + ".e00", true);
                                File.Delete(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00");
                            }
                        }
                    }
                }
                else
                {
                    IQueryFilter pFilter = new QueryFilterClass();
                    pFilter.WhereClause = mStrFiter;
                    IFeatureLayerDefinition pFLayerDef = mFeatureLayer as IFeatureLayerDefinition;
                    if (pFLayerDef.DefinitionExpression == "" && pFLayerDef.DefinitionSelectionSet == null)
                    {
                        if (pFcls.FeatureCount(pFilter) == 0) return false;
                        ExpE00(pFwks, ((IDataset)pFcls).Name, pFilter, mStrPath);
                    }
                    else
                    {
                        IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                        CopyFeatures(mFeatureLayer, pNewFcls, pFilter);
                        if (pNewFcls.FeatureCount(null) == 0) return false;
                        ExpE00(pFwks, ((IDataset)pNewFcls).Name, pFilter, mStrPath);
                        try
                        {
                            // Marshal.ReleaseComObject(pFwks);
                            // pFwks = null;
                            if (((IDataset)pNewFcls).CanDelete())
                            {
                                ((IFeatureWorkspaceManage)pFwks).DeleteByName(((IDataset)pNewFcls).FullName as IDatasetName);
                                ((IDataset)pNewFcls).Delete();
                            }

                        }
                        catch (System.Exception)
                        {
                        }
                        if (File.Exists(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00"))
                        {
                            File.Copy(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00", mStrPath + "\\" + mTargetFileNam + ".e00", true);
                            File.Delete(mStrPath + "\\" + ((IDataset)pNewFcls).Name + ".e00");
                        }
                    }
                }

                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }
        **/
        /// <summary>
        /// 在指定条件下，图层上是否有要素
        /// </summary>
        /// <param name="pFeatureLayer"></param>
        /// <param name="pFilterGeometry"></param>
        /// <param name="strFilter"></param>
        /// <returns></returns>
        private bool FeatureLayerHasFeatures(IFeatureLayer pFeatureLayer, IQueryFilter pFilter)
        {
            IFeatureCursor pFcursor = pFeatureLayer.Search(null , false);
            if (pFcursor == null) return false;
            
            IFeature pFeature = pFcursor.NextFeature();
            Marshal.ReleaseComObject(pFcursor);
            pFcursor = null;
            return pFeature != null;
        }

        /// <summary>
        /// create a new featureclass based on the template featureclass
        /// </summary>
        /// <param name="pTemplateFeatureClass"></param>
        /// <returns></returns>
        private IFeatureClass CreateFeatureClass(IFeatureClass pTemplateFeatureClass, IFeatureWorkspace pTargetWks)
        {
            try
            {
                IFeatureClass pNewFeatureClass;
                string strNewFclsName;
                string strTemplateFclsName = ((IDataset)pTemplateFeatureClass).Name;
                if ((((IDataset)pTemplateFeatureClass).Workspace).Type == esriWorkspaceType.esriRemoteDatabaseWorkspace && strTemplateFclsName.IndexOf(".") > 0)
                {
                    strTemplateFclsName = strTemplateFclsName.Substring(strTemplateFclsName.IndexOf(".") + 1);
                }

                IWorkspace2 pWks = pTargetWks as IWorkspace2;
                int index = -1;
                if (((IWorkspace)pTargetWks).Type != esriWorkspaceType.esriFileSystemWorkspace)
                {
                    while (true)
                    {
                        index++;
                        if (index == 0)
                        {
                            strNewFclsName = strTemplateFclsName;
                        }
                        else
                        {
                            strNewFclsName = strTemplateFclsName + "_" + index;
                        }
                        if (pWks.get_NameExists(esriDatasetType.esriDTFeatureClass, strNewFclsName) == false)
                        {
                            break;
                        }
                    }
                }
                else
                {
                    while (true)
                    {
                        index++;
                        if (index == 0)
                        {
                            strNewFclsName = strTemplateFclsName;
                        }
                        else
                        {
                            strNewFclsName = strTemplateFclsName + "_" + index;
                        }
                        if (System.IO.File.Exists(((IWorkspace)pTargetWks).PathName + "\\" + strNewFclsName + ".shp") == false)
                        {
                            break;
                        }
                    }
                }

                IClone pClone = pTemplateFeatureClass.Fields as IClone;
                if (pTemplateFeatureClass.FeatureType == esriFeatureType.esriFTAnnotation)
                {
                    pNewFeatureClass = GeodatabaseHelper.CreateAnnotationFeatureClass((IWorkspace)pTargetWks, strNewFclsName, pClone.Clone() as IFields, pTemplateFeatureClass);
                }
                else
                {
                    pNewFeatureClass = pTargetWks.CreateFeatureClass(strNewFclsName, pClone.Clone() as IFields, null, null, pTemplateFeatureClass.FeatureType, pTemplateFeatureClass.ShapeFieldName, "");
                }
                return pNewFeatureClass;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
                return null;
            }
        }

        private void CopyFeatures(IFeatureClass pSrcFcls, IFeatureClass pTargetFcls, IQueryFilter pFilter)
        {
            IFeatureCursor pTargetFCursor = null;
            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFcursor = pSrcFcls.Search(pFilter, false  );
            IFeature pFeature = pFcursor.NextFeature();
            if (pFeature == null) return;
            while (pFeature != null)
            {
                pTargetFCursor = pTargetFcls.Insert(true);
                pFeatureBuffer = pTargetFcls.CreateFeatureBuffer();

                if (pTargetFcls.FeatureType != esriFeatureType.esriFTAnnotation)
                {
                    pFeatureBuffer.Shape = pFeature.ShapeCopy;
                    for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                    {
                        if (pFeatureBuffer.Fields.get_Field(i).Editable && pFeatureBuffer.Fields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                            pFeatureBuffer.set_Value(i, pFeature.get_Value(i));
                    }
                }
                else
                {
                    pTargetFCursor = pTargetFcls.Insert(true);
                    pFeatureBuffer = pTargetFcls.CreateFeatureBuffer();
                    IAnnotationFeature pSrcAnnoFeature = pFeature as IAnnotationFeature;
                    IAnnotationFeature pTargetAnnoFeature = pFeatureBuffer as IAnnotationFeature;
                    ITextElement pTxtElement = new TextElementClass();
                    pTxtElement.Text = ((ITextElement)pSrcAnnoFeature.Annotation).Text;
                    IElement pElement = pTxtElement as IElement;
                    pElement.Geometry = pFeature.Shape.Envelope.LowerLeft;
                    pTxtElement.Symbol = ((ITextElement)pSrcAnnoFeature.Annotation).Symbol;
                    pTxtElement.Symbol.HorizontalAlignment = esriTextHorizontalAlignment.esriTHACenter;
                    pTxtElement.Symbol.VerticalAlignment = esriTextVerticalAlignment.esriTVACenter;
                    pTargetAnnoFeature.Annotation = pTxtElement as IElement;
                    pTargetFCursor.InsertFeature(pFeatureBuffer);
                }

                pTargetFCursor.InsertFeature(pFeatureBuffer);
                Marshal.ReleaseComObject(pFeature);
                pFeature = pFcursor.NextFeature();
            }
            System.Windows.Forms.Application.DoEvents();
            pTargetFCursor.Flush();
            Marshal.ReleaseComObject(pFcursor);
            pFcursor = null;
            Marshal.ReleaseComObject(pTargetFCursor);
            pTargetFCursor = null;
           
        }
        private void CopyFeatures(IFeatureLayer pSrcFeatureLayer, IFeatureClass pTargetFcls, IQueryFilter pFilter)
        {
            IFeatureCursor pTargetFCursor = null;
            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFcursor = pSrcFeatureLayer.Search(pFilter, false);
            IFeature pFeature = pFcursor.NextFeature();
            if (pFeature == null) return;
            while (pFeature != null)
            {
                pTargetFCursor = pTargetFcls.Insert(true);
                pFeatureBuffer = pTargetFcls.CreateFeatureBuffer();

                pFeatureBuffer.Shape = pFeature.ShapeCopy;
                for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                {
                    if (pFeatureBuffer.Fields.get_Field(i).Editable && pFeatureBuffer.Fields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                        pFeatureBuffer.set_Value(i, pFeature.get_Value(i));
                }

                pTargetFCursor.InsertFeature(pFeatureBuffer);
                Marshal.ReleaseComObject(pFeature);
                pFeature = pFcursor.NextFeature();
            }
            pTargetFCursor.Flush();
            System.Windows.Forms.Application.DoEvents();
            Marshal.ReleaseComObject(pFcursor);
            pFcursor = null;
            Marshal.ReleaseComObject(pTargetFCursor);
            pTargetFCursor = null;

        }
        private void ClipFeatureClass(IFeatureClass pSrcFcls, IFeatureClass pTargetFcls, IQueryFilter pFilter, IGeometry pClipGeometry)
        {
            try
            {
                IFeatureCursor pTargetFCursor = null;
                IFeatureBuffer pFeatureBuffer;
                IFeatureCursor pFcursor = pSrcFcls.Search(pFilter, false  );
                IFeature pFeature = pFcursor.NextFeature();
                if (pFeature == null) return;

                ITopologicalOperator2 pTopoOp;
                IRelationalOperator pRelOp;
                pTopoOp = pClipGeometry as ITopologicalOperator2;
                pTopoOp.IsKnownSimple_2 = false;
                pTopoOp.Simplify();
                pRelOp = pClipGeometry as IRelationalOperator;
                IGeometry pNewGeometry;
                IField pGeometryFld = pSrcFcls.Fields.get_Field(pSrcFcls.FindField(pSrcFcls.ShapeFieldName));
                IGeometryDef pGeometryDef = pGeometryFld.GeometryDef;
                while (pFeature != null)
                {
                    pTargetFCursor = pTargetFcls.Insert(true);
                    pFeatureBuffer = pTargetFcls.CreateFeatureBuffer();
                    IGeometry pGeo = pFeature.ShapeCopy;
                    ITopologicalOperator2 pTopoOp2 = pGeo as ITopologicalOperator2;
                    pTopoOp2.IsKnownSimple_2 = false;
                    pTopoOp2.Simplify();
                    if (pClipGeometry.SpatialReference.Equals(pGeo.SpatialReference) == false)
                    {
                        pClipGeometry.Project(pGeo.SpatialReference);
                    }
                    if (pRelOp.Overlaps(pGeo) || pRelOp.Crosses(pGeo) || pRelOp.Within(pGeo))
                    {
                        pNewGeometry = pTopoOp.Intersect(pGeo, pGeo.Dimension);
                        pNewGeometry.SpatialReference = pGeo.SpatialReference;
                        if (HasZ(pTargetFcls)) UpdateGeometryZ(pNewGeometry, 0);
                        ((ITopologicalOperator2)pNewGeometry).Simplify();
                        pFeatureBuffer.Shape = pNewGeometry;
                    }
                    else
                    {
                        pFeatureBuffer.Shape = pFeature.ShapeCopy;
                    }
                    for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                    {
                        if (pFeatureBuffer.Fields.get_Field(i).Editable && pFeatureBuffer.Fields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                            pFeatureBuffer.set_Value(i, pFeature.get_Value(i));
                    }
                    pTargetFCursor.InsertFeature(pFeatureBuffer);
                    pFeature = pFcursor.NextFeature();
                }

                pTargetFCursor.Flush();
                System.Windows.Forms.Application.DoEvents();

                Marshal.ReleaseComObject(pFcursor);
                pFcursor = null;
                Marshal.ReleaseComObject(pTargetFCursor);
                pTargetFCursor = null;
            }
            catch (System.Exception)
            {
            }

        }
        private void ClipFeatureClass(IFeatureLayer pSrcFlayer, IFeatureClass pTargetFcls, IQueryFilter pFilter, IGeometry pClipGeometry)
        {
            try
            {
                IFeatureCursor pTargetFCursor = null;
                IFeatureBuffer pFeatureBuffer;
                IFeatureCursor pFcursor = pSrcFlayer.Search(pFilter, false);
                IFeature pFeature = pFcursor.NextFeature();
                if (pFeature == null) return;

                ITopologicalOperator2 pTopoOp;
                IRelationalOperator pRelOp;
                pTopoOp = pClipGeometry as ITopologicalOperator2;
                pTopoOp.IsKnownSimple_2 = false;
                pTopoOp.Simplify();
                pRelOp = pClipGeometry as IRelationalOperator;
                IGeometry pNewGeometry;
                IField pGeometryFld = pSrcFlayer.FeatureClass.Fields.get_Field(pSrcFlayer.FeatureClass.FindField(pSrcFlayer.FeatureClass.ShapeFieldName));
                IGeometryDef pGeometryDef = pGeometryFld.GeometryDef;
                while (pFeature != null)
                {
                    pTargetFCursor = pTargetFcls.Insert(true);
                    pFeatureBuffer = pTargetFcls.CreateFeatureBuffer();
                    IGeometry pGeo = pFeature.ShapeCopy;
                    ITopologicalOperator2 pTopoOp2 = pGeo as ITopologicalOperator2;
                    pTopoOp2.IsKnownSimple_2 = false;
                    pTopoOp2.Simplify();
                    if (pClipGeometry.SpatialReference.Equals(pGeo.SpatialReference) == false)
                    {
                        pClipGeometry.Project(pGeo.SpatialReference);
                    }
                    if (pRelOp.Overlaps(pGeo) || pRelOp.Crosses(pGeo) || pRelOp.Within(pGeo))
                    {
                        pNewGeometry = pTopoOp.Intersect(pGeo, pGeo.Dimension);
                        pNewGeometry.SpatialReference = pGeo.SpatialReference;
                        if (HasZ(pTargetFcls)) UpdateGeometryZ(pNewGeometry, 0);
                        ((ITopologicalOperator2)pNewGeometry).Simplify();
                        pFeatureBuffer.Shape = pNewGeometry;
                    }
                    else
                    {
                        pFeatureBuffer.Shape = pFeature.ShapeCopy;
                    }
                    for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                    {
                        if (pFeatureBuffer.Fields.get_Field(i).Editable && pFeatureBuffer.Fields.get_Field(i).Type != esriFieldType.esriFieldTypeGeometry)
                            pFeatureBuffer.set_Value(i, pFeature.get_Value(i));
                    }
                    pTargetFCursor.InsertFeature(pFeatureBuffer);
                    pFeature = pFcursor.NextFeature();
                }

                pTargetFCursor.Flush();
                System.Windows.Forms.Application.DoEvents();

                Marshal.ReleaseComObject(pFcursor);
                pFcursor = null;
                Marshal.ReleaseComObject(pTargetFCursor);
                pTargetFCursor = null;
            }
            catch (System.Exception)
            {
            }

        }

        private IGeometry ClipGeometry(IGeometry pGeometry)
        {
            IGeometry pNewGeometry = new PolygonClass();
            IGeometryCollection pGC = (IGeometryCollection)pNewGeometry;
            object miss = Type.Missing;
            pGC.AddGeometry(pGeometry, ref miss, ref miss);
            IRelationalOperator pRelOp = mFilterGeometry as IRelationalOperator;
            pRelOp = (IRelationalOperator)pGeometry;
            ITopologicalOperator2 pTopoOp2 = pGeometry as ITopologicalOperator2;
            pTopoOp2.IsKnownSimple_2 = false;  
            pTopoOp2.Simplify();
            ITopologicalOperator2 pTopoOp = mFilterGeometry as ITopologicalOperator2;
            pTopoOp.IsKnownSimple_2 = false;
            pTopoOp.Simplify();
            if (mFilterGeometry.SpatialReference !=null &&  mFilterGeometry.SpatialReference.Equals(pGeometry.SpatialReference) == false)
            {
                mFilterGeometry.Project(pGeometry.SpatialReference);
            }
            if (pRelOp.Contains(pGeometry))
            {
                return pNewGeometry;
            }
                pNewGeometry = pTopoOp.Intersect(pGeometry, pGeometry.Dimension);
                pNewGeometry.SpatialReference = pGeometry.SpatialReference;
                //if (blnHasZ) UpdateGeometryZ(pNewGeometry, 0);
                ((ITopologicalOperator2)pNewGeometry).Simplify();
                
           
            return pNewGeometry;
        }


        private bool HasZ(IFeatureClass pFcls)
        {
            IField pFld = pFcls.Fields.get_Field(pFcls.FindField(pFcls.ShapeFieldName));
            IGeometryDef pGeometryDef = pFld.GeometryDef;
            return pGeometryDef.HasZ;
        }

        private void UpdateGeometryZ(IGeometry pGeometry, double dblZ)
        {
            IZAware pZArare = pGeometry as IZAware;
            pZArare.ZAware = true;
            IZ pZ = pGeometry as IZ;
            if (pZ != null) pZ.SetConstantZ(dblZ);

        }

        private string GetStyleByFeature(IFeature pFeature)
        {
            string strFcode = "";
            string strStyle = "";
            string[] strFcodeFileds = new string[4] { "FCODE", "CODE", "分类代码", "代码" };
            foreach (string str in strFcodeFileds)
            {
                int index = pFeature.Fields.FindField(str);
                if (index >= 0)
                {
                    strFcode = pFeature.get_Value(index).ToString().Trim();
                    break;
                }
            }
            if (strFcode == "") return "";
            string sql = "fcode='" + strFcode + "'";
            System.Data.DataRow [] pRows= mCadFcodeTable.Select(sql );
            foreach (System.Data.DataRow pRow in pRows)
            {
                if (pRow["style"] != DBNull.Value)
                {
                    if (pRow["style"].ToString().Trim() != "NONE")
                    {
                        strStyle = pRow["style"].ToString().Trim();
                        break;
                    }
                }
            }
            return strStyle;
        }
        private string GetSouthCode(string strFcode)
        {
            string strSouth_code="";
            if (strFcode == "") return "";
            System.Data.DataRow[] pRows = mCadFcodeTable.Select("fcode='" + strFcode + "'");
            if (pRows.Length > 0)
            {
                strSouth_code = pRows[0]["south_code"].ToString(); 
            }
            return strSouth_code;
        }


        private double  GetAngleByFeature(IFeature pFeature)
        {
            double dblAngle=0;           
            string[] strFileds = new string[3] { "ANGLE","FANGLE", "旋转角度" };
            foreach (string str in strFileds)
            {
                int index = pFeature.Fields.FindField(str);
                if (index >= 0)
                {
                    object obj = pFeature.get_Value(index);
                    if (obj != DBNull.Value)
                    {
                        string strValue = obj.ToString().Trim();
                        double dblValue;
                        if (double.TryParse(strValue, out  dblValue))
                        {
                            dblAngle = dblValue;
                            break;
                        }
                    }
                }
            }
            return dblAngle;
        }
        public bool ExportMif(ESRI.ArcGIS.Geoprocessor.Geoprocessor GP, QuickExport pQuickEpTool)
        {                                  
            if (mFeatureLayer == null) return false;
            try
            {              
                IFeatureClass pFcls = mFeatureLayer.FeatureClass;
                IDataset pDst = pFcls as IDataset;
                string strDstName = pDst.Name;
                if (strDstName.IndexOf(".") >= 0) strDstName = strDstName.Substring(strDstName.IndexOf(".") + 1);              
                if (mStrFiter != "")
                {
                    ESRI.ArcGIS.AnalysisTools.Select pSelectByAttribute = new ESRI.ArcGIS.AnalysisTools.Select();
                    pSelectByAttribute.in_features = GetGpDsPath(pFcls);
                    pSelectByAttribute.out_feature_class = ((IWorkspace)mTempWks).PathName + "\\" + strDstName;
                    pSelectByAttribute.where_clause = mStrFiter;
                    if (!RunTool(GP, pSelectByAttribute, null))
                    {
                        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                        return false;
                    }
                    try
                    {
                        pFcls = mTempWks.OpenFeatureClass(pDst.Name);
                    }
                    catch (System.Exception) { }
                    if (pFcls == null)
                    {
                        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                        return false;
                    }
                    pDst = pFcls as IDataset;
                    System.Windows.Forms.Application.DoEvents();
                }
                if (mFilterGeometry != null)
                {
                    if (mBlnClip && pFcls.FeatureType== esriFeatureType.esriFTSimple  && (pFcls.ShapeType == esriGeometryType.esriGeometryPolyline || pFcls.ShapeType == esriGeometryType.esriGeometryPolygon))
                    {
                        ESRI.ArcGIS.AnalysisTools.Intersect pIntersect = new ESRI.ArcGIS.AnalysisTools.Intersect();
                        pIntersect.in_features = GetGpDsPath(pFcls)+" ; "+GetGpDsPath(mClipFcls );
                        string strNewFclsName =strDstName  + "_Intersect";

                        pIntersect.out_feature_class = ((IWorkspace)mTempWks).PathName + "\\" + strNewFclsName;
                        if (!RunTool(GP, pIntersect, null))
                        {
                            LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                            return false;
                        }
                        if (((IDataset)pFcls).Workspace == mTempWks)
                        {
                            ((IDataset)pFcls).Delete();
                        }
                        try
                        {
                            pFcls = mTempWks.OpenFeatureClass(strNewFclsName);
                        }
                        catch (System.Exception) { }
                        if (pFcls == null)
                        {
                            LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                            return false;
                        }
                        pDst = pFcls as IDataset;
                        try
                        {
                            pDst.Rename(strDstName );
                        }
                        catch (System.Exception) { }
                        System.Windows.Forms.Application.DoEvents();
                    }
                    else
                    {
                        IFeatureClass pNewFcls = CreateFeatureClass(pFcls, mTempWks);
                        ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                        pSpatialFitler.Geometry = mFilterGeometry;
                        pSpatialFitler.GeometryField = mFeatureLayer.FeatureClass.ShapeFieldName;
                        pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                        CopyFeatures(pFcls, pNewFcls, pSpatialFitler);
                        pFcls = pNewFcls;
                        GC.Collect();
                        System.Windows.Forms.Application.DoEvents();
                    }
                }
                if (pFcls.FeatureCount(null) == 0)
                {
                    LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'上的满足条件的要素个数为零");
                    return false;

                }
                bool bln= Fcls2Mif(GP, pQuickEpTool, pFcls);
                //if (!bln)
                //{
                //    LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                //}
                //else
                //{
                //    LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出成功");
                //}
                System.Windows.Forms.Application.DoEvents();
                try
                {
                    if (((IDataset)pFcls).Workspace == mTempWks)
                    {
                        ((IDataset)pFcls).Delete();
                    }
                }
                catch (System.Exception)
                {
                }
                return bln;
              
                //IFeatureClass pNewFcls = null;
                //IFeatureWorkspace pFwks = ((IDataset)pFcls).Workspace as IFeatureWorkspace;
                //ISpatialFilter pSpatialFitler = new SpatialFilterClass();
                //if(mFilterGeometry !=null )
                //pSpatialFitler.Geometry = mFilterGeometry;
                //pSpatialFitler.GeometryField = mFeatureLayer.FeatureClass.ShapeFieldName;
                //pSpatialFitler.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                //pSpatialFitler.WhereClause = mStrFiter;               
                //if(mFilterGeometry !=null || mStrFiter !="" )
                //{                   
                //     pNewFcls = CreateFeatureClass(pFcls, mTempWks);                    
                //    if (mFilterGeometry != null && mBlnClip && (pFcls.ShapeType == esriGeometryType.esriGeometryPolygon || pFcls.ShapeType == esriGeometryType.esriGeometryPolyline))
                //    {
                //        ClipFeatureClass(pFcls, pNewFcls, pSpatialFitler, mFilterGeometry);
                //    }
                //    else
                //    {
                //        CopyFeatures(pFcls, pNewFcls, pSpatialFitler);
                //    }
                //    System.Windows.Forms.Application.DoEvents();
                //    if (pNewFcls.FeatureCount(null) == 0)
                //    {
                //        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'上的满足条件的要素个数为零");
                //        return false;
                //    }
                //    GC.Collect();
                //    if (Fcls2Mif(GP, pQuickEpTool, pNewFcls, ((IDataset)pFcls).Name))
                //    {
                //        LogHelper.WriteLog("图层'"+mFeatureLayer.Name +"'导出成功");
                //    }
                //    else
                //    {
                //        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                //    }
                //    try
                //    {
                //        ((IDataset)pNewFcls).Delete();
                //    }
                //    catch (Exception ex)
                //    {
                //          MsgHelper.ShowWarningMsgbox(ex.Message);
                //    }                   
                //}
                //else
                //{                    
                //    if (Fcls2Mif(GP, pQuickEpTool, pFcls, ((IDataset)pFcls).Name))
                //    {
                //        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出成功");
                //    }
                //    else
                //    {
                //        LogHelper.WriteLog("图层'" + mFeatureLayer.Name + "'导出失败");
                //    }
                //}
                //System.Windows.Forms.Application.DoEvents();


                //return true;
            }
            catch (System.Exception ex)
            {
                LogHelper.WriteLog(ex);
                return false;
            }
        }
        private bool  Fcls2Mif(ESRI.ArcGIS.Geoprocessor.Geoprocessor GP, QuickExport pQuickEpTool,IFeatureClass pFcls)
        {
            IDataset pDst = pFcls as IDataset;
            string strFclsPath = "";
            string strInput;    
            switch (pDst.Workspace.Type)
            {
                case esriWorkspaceType.esriFileSystemWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    strInput = strFclsPath + "\\" + pDst.Name+".shp";
                    break;
                case esriWorkspaceType.esriLocalDatabaseWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    strInput = strFclsPath + "\\" + pDst.Name;
                    break;
                case esriWorkspaceType.esriRemoteDatabaseWorkspace:
                    string strSdeFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\temp.sde";
                    if (File.Exists(strSdeFile)) File.Delete(strSdeFile);
                    
                        IWorkspaceFactory pWksFac = new SdeWorkspaceFactoryClass();
                        pWksFac.Create(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "temp.sde", pDst.Workspace.ConnectionProperties, 0);
                   
                    strInput = strSdeFile + "\\" + pDst.Name;
                    break;
                default:
                    {
                        return false ;
                    }
            }                      
            pQuickEpTool.Input = strInput;
            if (mStrPath.EndsWith("\\") == false) mStrPath += "\\";
            pQuickEpTool.Output = @"mif,"+mStrPath;
            bool bln = RunTool(GP, pQuickEpTool, null);          
            return bln;
        }
        private bool Fcls2Mif(ESRI.ArcGIS.Geoprocessor.Geoprocessor GP, QuickExport pQuickEpTool, string strInputFcls, string strTargetName)
        {

            pQuickEpTool.Input = strInputFcls;
            if (mStrPath.EndsWith("\\") == false) mStrPath += "\\";
            pQuickEpTool.Output = mStrPath+strTargetName+".mif";
            bool bln = RunTool(GP, pQuickEpTool, null);
            return bln;
        }

        private bool RunTool(Geoprocessor geoprocessor, IGPProcess process, ESRI.ArcGIS.esriSystem.ITrackCancel TC)
        {
            bool blnResult = false;
            // Set the overwrite output option to true
            geoprocessor.OverwriteOutput = true;
            IGeoProcessorResult objResult = null;

            // Execute the tool            
            try
            {
                objResult = geoprocessor.Execute(process, null) as IGeoProcessorResult;
                System.Windows.Forms.Application.DoEvents();
                if (objResult != null)
                {
                    if (objResult.Status == esriJobStatus.esriJobSucceeded)
                    {
                        blnResult = true;
                    }
                }
                else
                {
                    if (geoprocessor.MessageCount == 0)
                    {
                        blnResult = true;
                    }
                    else
                    {
                        blnResult = false;
                    }
                }

                if (!blnResult)
                {
                    OutputMessages(geoprocessor);
                }


            }
            catch (Exception err)
            {
                Console.WriteLine(err.Message);
                OutputMessages(geoprocessor);
            }
            finally
            {
                //if (process != null && System.Runtime.InteropServices.Marshal.IsComObject(process))
                //{
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(process);
                //    process = null;
                //}
                //if (objResult != null && System.Runtime.InteropServices.Marshal.IsComObject(objResult))
                //{
                //    System.Runtime.InteropServices.Marshal.ReleaseComObject(objResult);
                //    objResult = null;
                //}

            }
            return blnResult;
        }
        private void OutputMessages(Geoprocessor gp)
        {
            //RuleLog objLog= RuleLog.GetRuleLogObject(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\RuleLog.log");
            if (gp.MessageCount > 0)
            {               
                for (int Count = 0; Count <= gp.MessageCount - 1; Count++)
                {
                    Console.WriteLine(gp.GetMessage(Count));                 

                }
            }
            gp.ClearMessages();

        }

        private string GetGpDsPath(IFeatureClass pFcls)
        {
            IDataset pDst = pFcls as IDataset;
            string strFclsPath = "";
            string strInput;
            
            switch (pDst.Workspace.Type)
            {
                case esriWorkspaceType.esriFileSystemWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    strInput = strFclsPath + "\\" + pDst.Name + ".shp";
                    break;
                case esriWorkspaceType.esriLocalDatabaseWorkspace:
                    strFclsPath = pDst.Workspace.PathName;
                    //if (strFeatureDstName == "")
                    //{
                        strInput = strFclsPath + "\\" + pDst.Name;
                    //}
                    //else
                    //{
                    //    strInput = strFclsPath + "\\"+strFeatureDstName+"\\" + pDst.Name;
                    //}
                   
                    break;
                case esriWorkspaceType.esriRemoteDatabaseWorkspace:
                    string strSdeFile = System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\temp.sde";
                    if (!File.Exists(strSdeFile))
                    {
                        IWorkspaceFactory pWksFac = new SdeWorkspaceFactoryClass();
                        pWksFac.Create(System.IO.Path.GetDirectoryName(this.GetType().Assembly.Location), "temp.sde", pDst.Workspace.ConnectionProperties, 0);
                    }
                    strInput = strSdeFile + "\\" + pDst.Name;
                    break;
                default:
                    {
                        return "";
                    }
            }
            return strInput;
        }
    }
}
